/**
 * 
 */
package routing;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Scanner;

import network.IPPacket;

import org.apache.log4j.Logger;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleWeightedGraph;
import org.springframework.beans.factory.annotation.Autowired;

import routing.route.Route;
import routing.table.RouteTable;

/**
 * @author chevy
 *
 */
public class Router {
	
	private String hostName;
	
	private RouteTable routingTable;
	
	private SimpleWeightedGraph<String, DefaultEdge> topology;
	
	private RoutingProtocol protocol;
	
	public Router(String name, String path_file)
	{
		hostName = name;
		topology = 
			new SimpleWeightedGraph<String, DefaultEdge>(DefaultEdge.class);
		
		try {
			InputStream fileName = Thread.currentThread().getContextClassLoader().getResource(path_file).openStream();
			Scanner scan = new Scanner(fileName);
			while (scan.hasNext()) {
				String currentLine = scan.next();
				String[] edges = currentLine.split(",");
				topology.addVertex(edges[0]);
				topology.addVertex(edges[1]);
				topology.addEdge(edges[0], edges[1]);
			}
			scan.close();
		} catch (FileNotFoundException e) {
			Logger logger = Logger.getLogger("com.foo");
			logger.error(
					String.format("No se encontró el archivo %s", path_file), e);
		} catch (IOException e) {
			Logger logger = Logger.getLogger("com.foo");
			logger.error(
					String.format("No se encontró el archivo %s", path_file), e);
		}
	}
	
	private void createTable(){
	
		routingTable = protocol.createTable(hostName, topology);
		
	}
	
	@Autowired
	public void setProtocol(RoutingProtocol protocol) {
		this.protocol = protocol;
		createTable();
		HashMap<String, Double> loop = new HashMap<String, Double>();
		loop.put("loopback" + hostName, (double)0);
		Route loopback = new Route(hostName, loop, 0);
		routingTable.evaluateRoute(loopback);
	}

	@org.springframework.integration.annotation.Router
	public String routeMessage(IPPacket packet){
		String destinationAddress = packet.getDestinationAddress();
		String exitInterface = null;
		try {
			exitInterface = routingTable.routePacket(destinationAddress, protocol);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//System.out.println("Se enrutará del router " + hostName + " a " + exitInterface);
		return exitInterface;
	}
	
	@org.springframework.integration.annotation.ServiceActivator
	public void receivePakcket(IPPacket packet)
	{
		System.out.println(
				String.format("El router %s recivió un paquete de %s con el mensaje %s",
						hostName, packet.getSuourceDestination(), packet.getPayload()));
	}
	
}
